var http = require('../../../utils/https.js')
Page({
  data: {
    deliveryType: 'delivery', // 默认配送
    showDatePicker: false,
    showTimePicker: false,
    dateOptions: [],
    selectedDate: '', // 用于显示的文字（今天 8月5日）
    displayTime: '',
    timeValue: '',
    couponValue: 0,
    selfPickupAnimation: {},
    orderList: [], // 订单列表
    totalPrice: 0.0, // 总的订单金额
    isProductOrder: false, // 判断是否是直接购买
    // 收货地址列表
    deliveryAddresses: [{
      id: 1,
      address: '光谷软件园2号楼西门1111',
      room: '2号楼101室',
      name: '西瓜',
      gender: '女士',
      phone: '18888883945',
      selected: true,
      check: false
    }],
    address: '',
    people: '',
    returnValue: null,
    selfAddress: [],
    self: '',
    index: null,
    remark: '', // 订单备注

  },

  // 选择自提点地址
  chooseSelfAddress() {
    wx.navigateTo({
      url: '/my/pages/myselfAddress/myselfAddress',
    })
  },

  // 获取用户地址
  getAddress(userId) {
    var that = this
    http.GET('/user/address/listByUserId', {
      userId: userId
    }, function (res) {
      if (res.code === 200) {
        // console.log(res.data);
        var a = res.data
        // console.log("地址是：", a);
        that.setData({
          deliveryAddresses: a,
        })
        var index = 0
        // 无默认时 第一个地址为默认
        for (var i = 0; i < a.length; i++) {
          if (a[i].isDefault == 1) {
            index = i
            break
          }
        }
        var nowAddress = a[index].city + " " + a[index].district + " " + a[index].details
        var p = a[index].receiverName + "  " + a[index].receiverPhone
        that.setData({
          address: nowAddress,
          people: p,
          index: a[index].id
        })


      } else {
        wx.showToast({
          title: '登录过期',
          icon: 'none',
          duration: 1000
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/index/pages/mzhLogin/mzhLogin',
          })
        }, 1500)
      }
    }, function (err) {
      console.error('失败:', err);
    });
  },
  // 选择地址
  chooseAddress() {
    wx.navigateTo({
      url: '/index/pages/mzhAddress/mzhAddress',
    })
  },
  // 页面加载
  onLoad(options) {
    var userInfo = wx.getStorageSync('userInfo')
    if (userInfo == null || userInfo == undefined) {
      wx.showToast({
        title: '登陆过期',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/index/pages/mzhLogin/mzhLogin',
        })
      }, 1500)
    }

    this.getAddress(userInfo.userId)
    // var order = options.order
    console.log(options);
    // 判断是从购物车进入还是直接购买
    var order = null
    if (options.order != "") {
      this.setData({
        isProductOrder: false
      })
      order = JSON.parse(options.order);
    } else {
      this.setData({
        isProductOrder: true
      })
      order = JSON.parse(wx.getStorageSync('productOrder'))
      console.log(order);
      wx.removeStorageSync('productOrder')
    }
    var totalPrice = options.totalPrice
    this.setData({
      orderList: order,
      totalPrice: totalPrice
    })
    // console.log("订单是：", order);
    this.initDateOptions();
    const now = new Date();
    const rounded = this.getNextHalfHour(now);
    this.setData({
      timeValue: this.formatTimeForPicker(rounded)
    });

    this.initAnimations();
  },
  onShow() {
    var userInfo = wx.getStorageSync('userInfo')
    if (userInfo == null || userInfo == undefined) {
      wx.showToast({
        title: '登陆过期',
        icon: 'none',
        duration: 1000
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/index/pages/mzhLogin/mzhLogin',
        })
      }, 1500)
    }
    this.getAddress(userInfo.userId)

    var that = this
    var id = wx.getStorageSync('selfId') || null
    if (id != null) {
      http.GET(`/tool/pointpick/${id}`, {}, (res) => {
        // console.log('成功哈哈哈哈:', res);
        that.setData({
          self: res.data.name
        })
      }, (err) => {
        console.error('失败:', err);
      });
    }



  },

  // 初始化未来7天的日期选项
  initDateOptions() {
    const options = [];
    const today = new Date();

    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      let label = '';
      if (i === 0) {
        label = '今天';
      } else if (i === 1) {
        label = '明天';
      } else if (i === 2) {
        label = '后天';
      } else {
        const week = ['日', '一', '二', '三', '四', '五', '六'];
        label = `周${week[date.getDay()]}`;
      }

      const month = date.getMonth() + 1;
      const day = date.getDate();
      const labelText = `${label} ${month}月${day}日`;

      // 存 label 和实际值
      options.push({
        label: labelText,
        value: `${month}-${day}`
      });
    }

    // 把 label 列表单独提取给 picker 用
    const labels = options.map(item => item.label);

    this.setData({
      dateOptions: options,
      dateLabels: labels // 新增
    });
  },


  // 打开日期选择
  onSelectTime() {
    this.setData({
      showDatePicker: true
    });
  },

  // 关闭日期选择
  onCloseDatePicker() {
    this.setData({
      showDatePicker: false
    });
  },

  // 确认日期选择
  onConfirmDate(event) {
    const index = event.detail.index;
    const selected = this.data.dateOptions[index];

    this.setData({
      showDatePicker: false,
      selectedDate: selected.label // 展示用
    }, () => {
      this.setData({
        showTimePicker: true
      });
    });
  },

  // 关闭时间选择
  onCloseTimePicker() {
    this.setData({
      showTimePicker: false
    });
  },

  // 确认时间选择
  onConfirmTime(event) {
    // event.detail 是字符串或 Date，根据组件决定
    let timeStr = '';

    if (typeof event.detail === 'string') {
      timeStr = event.detail;
    } else if (event.detail instanceof Date) {
      timeStr = this.formatTimeForPicker(event.detail);
    } else if (event.detail.value) {
      timeStr = event.detail.value;
    }

    this.setData({
      showTimePicker: false,
      timeValue: timeStr,
      displayTime: `${this.data.selectedDate} ${timeStr}`
    });
  },

  // 格式化为 "HH:mm"
  formatTimeForPicker(date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${hours}:${minutes}`;
  },

  // 向上取整到下一个半小时
  getNextHalfHour(date) {
    const d = new Date(date);
    const minutes = d.getMinutes();
    if (minutes < 30) {
      d.setMinutes(30);
    } else {
      d.setHours(d.getHours() + 1);
      d.setMinutes(0);
    }
    d.setSeconds(0);
    d.setMilliseconds(0);
    return d;
  },

  // 其他不变
  initAnimations() {
    this.selfPickupAni = wx.createAnimation({
      duration: 300,
      timingFunction: 'ease-in-out'
    });
  },

  onDeliveryChange(event) {
    const isDelivery = event.detail;
    const deliveryType = isDelivery ? 'delivery' : 'self';

    if (deliveryType === 'self') {


      var selfId = wx.getStorageSync('selfId') || null
      // 如果没有自提点id
      if (selfId == null) {
        var that = this
        // 获取自提点的地址
        http.GET('/tool/pointpick/listAll', {}, (res) => {
          // console.log('成功:', res);
          if (res.code === 200) {
            that.setData({
              selfAddress: res.rows
            })
            var list = res.rows
            for (var i = 0; i < list.length; i++) {
              list[i].isDefault = false
            }
            list[0].isDefault = true
            that.setData({
              selfAddress: list,
              self: list[0].name,
            })
            wx.setStorageSync('selfId', list[0].id)
          }
        }, (err) => {
          console.error('失败:', err);
        });
      }
      this.selfPickupAni.height(0).opacity(0).step();
      this.setData({
        selfPickupAnimation: this.selfPickupAni.export()
      });

      setTimeout(() => {
        this.setData({
          deliveryType
        });
        setTimeout(() => {
          this.selfPickupAni.height('auto').opacity(1).step();
          this.setData({
            selfPickupAnimation: this.selfPickupAni.export()
          });
        }, 50);
      }, 300);
    } else {
      this.selfPickupAni.height(0).opacity(0).step();
      this.setData({
        selfPickupAnimation: this.selfPickupAni.export(),
        deliveryType
      });
    }
  },

  onSelectCoupon() {
    wx.showToast({
      title: '选择优惠券',
      icon: 'none'
    });
  },
  // 获取备注的内容
  onRemarkChange(e) {
    this.setData({
      remark: e.detail.value
    })
  },



  // 提交订单
  onClickButton() {
    // 订单备注
    console.log(this.data.remark);
    // 订单信息
    console.log(this.data.orderList);
    // 订单的配送方式
    console.log(this.data.deliveryType);
    var addressId = 0
    var flag = true
    if (this.data.deliveryType == 'self') {
      flag = false
      addressId = wx.getStorageSync('selfId')
    } else {
      addressId = this.data.index
    }

    // 订单的地址信息
    console.log(addressId);


    // 不是直接购买需要清除购物车里的信息
    if (this.data.isProductOrder == false) {
      var that = this
      var orderId = null
      http.POST('/order/orders/myAdd', {
        order: this.data.orderList,
        deliveryType: this.data.deliveryType,
        addressId: addressId,
        flag: flag,
        remark: this.data.remark
      }, function (res) {
        if (res.code === 200) {
          orderId = res.data

          if (that.data.deliveryType == "self") {
            // 自提订单
            wx.redirectTo({
              url: `/my/pages/xtxSelfNoPay/xtxSelfNoPay?orderId=${orderId}`,
            })
          } else {
            // 配送订单
            wx.redirectTo({
              url: `/my/pages/xtxNoPay/xtxNoPay?orderId=${orderId}`,
            })
          }
        }
      }, function (err) {
        console.error('失败:', err);
      });
    } else {
      console.log("这是直接购买商品");
      // 这是直接购买商品  /order/orders/isProductOrder
      var did = 0
      if (this.data.deliveryType != "delivery") {
        did = 1
      }
      var po = this.data.orderList[0]
      var isProduct = {
        userId: wx.getStorageSync('userInfo').userId,
        payId: 0,
        deliverId: did,
        totalAmount: po.price,
        remark: this.data.remark,

        // 订单明细表
        productId: po.id,
        productName: po.name,
        quantity: 1,
        unitPrice: po.price,
        subtotal: po.price,

        // 订单地址表
        addressId: addressId
      }

      console.log(isProduct);
      var that = this
      http.POST('/order/orders/isProductOrder', isProduct, (res) => {
        console.log('成功:', res);
        if(res.code===200){
          if(that.data.deliveryType=="self"){
            wx.navigateTo({
              url: `/my/pages/xtxSelfNoPay/xtxSelfNoPay?orderId=${res.data}`,
            })
          }else{
            wx.navigateTo({
              url: `/my/pages/xtxNoPay/xtxNoPay?orderId=${res.data}`,
            })
          }
        }else{
          wx.showToast({
            title: '登陆过期',
            icon:'none',
            duration:1000
          })
          setTimeout(()=>{
            wx.redirectTo({
              url: '/index/pages/mzhLogin/mzhLogin',
            })
          },1500)
        }
      }, (err) => {
        console.error('失败:', err);
      });

    }
  }
});